package com.authorization.demo.service.impl;

import com.alibaba.excel.EasyExcel;
import com.authorization.demo.entity.UserTable;
import com.authorization.demo.excel.entity.UserExcel;
import com.authorization.demo.excel.listener.UserExcelListener;
import com.authorization.demo.mapper.UserTableMapper;
import com.authorization.demo.service.UserTableService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

import static org.apache.poi.ss.util.CellUtil.createCell;

/**
 * @Remarks:
 * @ClassName: UserTableServiceImpl
 * @Author: Micora
 * @CreateTime: 2022/7/13
 */
@Service
@Slf4j
public class UserTableServiceImpl extends ServiceImpl<UserTableMapper, UserTable> implements UserTableService {

    @Resource
    private UserTableMapper userTableMapper;

    @Override
    public boolean FindOneIsExist(String userName) {
        if (userTableMapper.selectById(userName) != null) {
            return true;
        }
        return false;


    }

    //根据excel批量导入用户
    @Override
    public void ExcelImport(File file) throws IOException, InvalidFormatException {
        Workbook workbook = null;
        String fileName = file.getName();
        if (fileName.endsWith("xlsx")) {
            workbook = new XSSFWorkbook(file);
        } else if (fileName.endsWith("xls")) {
            workbook = new HSSFWorkbook(POIFSFileSystem.create(file));
        }
        Sheet sheet = workbook.getSheetAt(0);
        int physicalNumberOfRows = sheet.getPhysicalNumberOfRows();
        //格式检查
        log.info("格式检查开始");
        if (physicalNumberOfRows > 1) { //第二行才开始是用户数据，检查是否存在用户数据内容
            Row row0 = sheet.getRow(0);
            if (row0 != null) {
                Cell cell = row0.getCell(0);
                if (cell.getCellType() == CellType.STRING) {
                    if (!cell.getStringCellValue().equals("用户信息列表")) {
                        log.error("excel内容错误，第一行应为”用户信息列表“");
                        return;
                    }
                }
            }
            //TODO:第二行内容判断
        }
        log.info("格式检查结束");

        List<UserTable> userTableList = new ArrayList<UserTable>();
        for (int i = 2; i < physicalNumberOfRows; i++) {
            Row row = sheet.getRow(i);
            if (row != null) {
                UserTable userTable = new UserTable();
                if (row.getCell(0) != null) {
                    if (row.getCell(0).getCellType() != CellType.STRING) {
                        row.getCell(0).setCellType(CellType.STRING);
                    }
                    userTable.setUserName(row.getCell(0).getStringCellValue());
                }
                if (row.getCell(1) != null) {
                    if (row.getCell(1).getCellType() != CellType.STRING) {
                        row.getCell(1).setCellType(CellType.STRING);
                    }
                    userTable.setName(row.getCell(1).getStringCellValue());
                }
                if (row.getCell(2) != null) {
                    if (row.getCell(2).getCellType() != CellType.STRING) {
                        row.getCell(2).setCellType(CellType.STRING);
                    }
                    userTable.setPassword(row.getCell(2).getStringCellValue());
                }

                if (row.getCell(3) != null) {
                    if (row.getCell(3).getStringCellValue().equals("女")) {
                        userTable.setGender(2);
                    } else if (row.getCell(3).getStringCellValue().equals("男")) {
                        userTable.setGender(1);
                    } else {
                        userTable.setGender(0);
                    }
                }
                row.getCell(4).setCellType(CellType.STRING);
                userTable.setPhone(row.getCell(4).getStringCellValue());
                userTable.setMail(row.getCell(5).getStringCellValue());
                if (row.getCell(6) != null) {
                    if (row.getCell(6).getStringCellValue().equals("无效")) {
                        userTable.setStatus(1);
                    } else if (row.getCell(6).getStringCellValue().equals("有效")) {
                        userTable.setStatus(2);
                    } else {
                        userTable.setStatus(0);
                    }
                }
                if (row.getCell(7) != null) {
                    if (row.getCell(7).getCellType() != CellType.STRING) {
                        row.getCell(7).setCellType(CellType.STRING);
                    }
                    userTable.setRemarks(row.getCell(7).getStringCellValue());
                }
                userTableList.add(userTable);
            }
        }
        for (UserTable userTable : userTableList
             ) {
            userTableMapper.insert(userTable);
        }


    }

    //导出用户
    @Override
    public void exportUsers(String[] userNames) throws IOException {
        Workbook wb = new XSSFWorkbook();
        Sheet sheet = wb.createSheet("用户表");
        int rowLine = 0;

        //获取用户列表
        System.out.println(userNames.toString());
        List<UserTable> userTableList = this.listByIds(Arrays.asList(userNames));

//        Row headRow = sheet.createRow(rowLine++);  //创建标题行
//        headRow.setHeightInPoints(30);  //设置行高（可参见API等 ）
//        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 7));
//        Cell headCell = headRow.createCell(0);
//        headCell.setCellValue("用户信息列表");

        Row titleRow = sheet.createRow(rowLine++);//创建属性标题行
        Cell cell0 = titleRow.createCell(0);
        cell0.setCellValue("用户名username");
        Cell cell1 = titleRow.createCell(1);
        cell1.setCellValue("姓名name");
        Cell cell2 = titleRow.createCell(2);
        cell2.setCellValue("密码password");
        Cell cell3 = titleRow.createCell(3);
        cell3.setCellValue("性别gender");
        Cell cell4 = titleRow.createCell(4);
        cell4.setCellValue("手机phone");
        Cell cell5 = titleRow.createCell(5);
        cell5.setCellValue("邮箱mail");
        Cell cell6 = titleRow.createCell(6);
        cell6.setCellValue("状态status");
        Cell cell7 = titleRow.createCell(7);
        cell7.setCellValue("备注remarks");


        //逐行添加用户信息
        Iterator<UserTable> iterator = userTableList.iterator();
        while (iterator.hasNext()) {
            UserTable userTable = iterator.next();
            Row row = sheet.createRow(rowLine++);
            Cell rowCell0 = row.createCell(0);
            rowCell0.setCellValue(userTable.getUserName());
            Cell rowCell1 = row.createCell(1);
            rowCell1.setCellValue(userTable.getName());
            Cell rowCell2 = row.createCell(2);
            rowCell2.setCellValue(userTable.getPassword());
            Cell rowCell3 = row.createCell(3);
            rowCell3.setCellValue(userTable.getGender()==1?"男":(userTable.getGender()==2?"女":null));
            Cell rowCell4 = row.createCell(4);
            rowCell4.setCellValue(userTable.getPhone());
            Cell rowCell5 = row.createCell(5);
            rowCell5.setCellValue(userTable.getMail());
            Cell rowCell6 = row.createCell(6);
            rowCell6.setCellValue(userTable.getStatus()==1?"有效":"无效");
            Cell rowCell7 = row.createCell(7);
            rowCell7.setCellValue(userTable.getRemarks());
        }

        String path = "C:\\Users\\16270\\Desktop\\赛意练习\\模拟项目\\导出用户信息表.xlsx";
        FileOutputStream fos = new FileOutputStream(path);

        wb.write(fos);
        fos.close();
        //TODO:删除文件
    }

    @Override
    public void importExcel(MultipartFile file, UserTableService userService) {
        try {
            //文件输入流
            InputStream in = file.getInputStream();
            //调用方法进行读取
            EasyExcel.read(in, UserExcel.class,new UserExcelListener(userService)).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void exportExcel(HttpServletResponse response, String[] userNames) {
        //设置下载信息
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = null;
        try {
            fileName = URLEncoder.encode("用户信息","UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        response.setHeader("Content-disposition","attachment;filename="+fileName+".xlsx");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        List<UserExcel> excelUserList = new ArrayList<>();
        if (userNames.length != 0) {
            List<UserTable> userTableList = this.listByIds(Arrays.asList(userNames));
            userTableList.forEach(userTable -> {
                UserExcel userExcel = new UserExcel();
                BeanUtils.copyProperties(userTable, userExcel);
                excelUserList.add(userExcel);
            });
        }

        //调用方法实现写操作
        try {
            EasyExcel.write(response.getOutputStream(),UserExcel.class).sheet("用户信息").doWrite(excelUserList);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
